const express = require('express');
const axios = require('axios');
const cors = require('cors');
const app = express();
const port = 3000;

app.use(cors());
app.use(express.json()); // 确保解析 JSON 请求体

app.post('/proxy', async (req, res) => {
    console.log('Received request body:', req.body);  // 打印请求体
    console.log('Received request headers:', req.headers);  // 打印请求头

    try {
        const response = await axios({
            method: 'post',
            url: 'https://spark-api-open.xf-yun.com/v1/chat/completions',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': req.headers.authorization // 从请求头中获取授权信息
            },
            data: req.body,
            responseType: 'stream'  // 如果需要流式响应，确保设置正确的响应类型
        });

        console.log('Proxy response status:', response.status);  // 打印代理响应状态码
        console.log('Proxy response headers:', response.headers);  // 打印代理响应头

        // 流式处理响应数据
        response.data.pipe(res);
    } catch (error) {
        console.error('Error in proxy request:', error.response ? error.response.data : error.message);
        res.status(500).send('Server error');
    }
});

app.listen(port, () => {
    console.log(`CORS proxy server is running on http://localhost:${port}`);
});